<template>
  <AntdGenerateForm
    ref="generateFormRef"
    style="margin-top: 20px"
    :is-show="state.previewVisible"
    :data="state.widgetForm"
    :disabled="props.disabled"
    :disabled-field-codes="disabledFieldCodes || []"
    :remote-replace="remoteReplace"
    :query-value-flag="queryValueFlag === 1"
    :preset-values="presetValues"
    :approval-permission="approvalPermission"
    @change="itemValueChange"
  />
</template>
<script lang="ts" setup>
import AntdGenerateForm from './AntdGenerateForm.vue';
import { reactive, ref, onMounted, watch, computed } from 'vue';
import { cloneDeep } from 'lodash-es';
import { setVal, attrs, antd, getDatePickerFormat } from './config';
import { fieldTypeOpstion } from './config/enum';
import { formDetail, formDetailApp } from '@/api/modules/form';
import { useUserStoreWidthOut } from '@/stores/user';

const props = defineProps<{
  formId: string;
  // 1: 平台层级; 2: 组织层级; 3: 业务层级; 4: 应用
  formBusinessLevel?: number;
  queryValueFlag?: number;
  disabled?: boolean;
  // 表单预置值
  presetValues?: object;
  // 替换参数值
  replaceVal?: any;
  // 需要禁用的字段
  disabledFieldCodes?: any[];
  approvalPermission?: boolean;
  projectId: string;
}>();

const state = reactive({
  previewVisible: false,
  widgetForm: cloneDeep(antd.widgetForm),
});
const generateFormRef = ref();

onMounted(() => {
  review();
});

watch(
  () => props.formId,
  () => {
    review();
  }
);

const emits = defineEmits(['itemValueChange', 'finishLoading']);

const review = () => {
  state.widgetForm.list = [];
  state.previewVisible = false;
  let fn: any = null;
  const params: any = {
    formId: props.formId,
  };
  if (props.formBusinessLevel === 4) {
    fn = formDetailApp;
    params.queryValueFlag = props.queryValueFlag;
  } else {
    fn = formDetail;
  }
  fn(params).then((res: any) => {
    const tempConfig = cloneDeep(res);
    delete tempConfig.fieldList;
    state.widgetForm.config = {
      ...tempConfig,
    };
    convertFieldListToShow(res.fieldList);
    state.previewVisible = true;
    finishLoading();
  });
};

/**
 * 通知父页面完成数据加载
 */
const finishLoading = () => {
  emits('finishLoading');
};

const convertFieldListToShow = (fieldArr: any[]) => {
  fieldArr.forEach((field) => {
    const typeObj = fieldTypeOpstion.find(
      (type) => type.value === field.fieldType
    );
    if (typeObj) {
      const componentObj = (antd as any)[typeObj.type].find(
        (item: any) => item.type === typeObj.code
      );
      if (componentObj) {
        convertFieldToShow(field, componentObj);
      }
    }
  });
};

const convertFieldToShow = (remoteField: any, localComponent: any) => {
  const tempItem = cloneDeep(localComponent);
  for (const key in remoteField) {
    const fieldAttr = attrs.find((item) => item.remote === key);
    if (fieldAttr) {
      if (key === 'dateFormat') {
        setVal(
          tempItem,
          fieldAttr.local,
          getDatePickerFormat(remoteField.dateType, remoteField.dateFormat)
            .value
        );
      } else {
        setVal(
          tempItem,
          fieldAttr.local,
          key === 'requiredFlag' ? !!remoteField[key] : remoteField[key]
        );
      }
    }
  }
  state.widgetForm.list.push(tempItem);
};

const getData = (isValidate = true) => {
  return new Promise((resolve, reject) => {
    generateFormRef.value
      .getData(isValidate)
      .then((res: any) => {
        resolve(cloneDeep(res));
      })
      .catch((err: any) => {
        reject(err);
      });
  });
};

const getBusinessData = (isValidate = true) => {
  return new Promise((resolve, reject) => {
    generateFormRef.value
      .getBusinessData(isValidate)
      .then((res: any) => {
        resolve(res);
      })
      .catch((err: any) => {
        reject(err);
      });
  });
};

const userStore = useUserStoreWidthOut();

const remoteReplace = computed(() => {
  let orgId;
  if (props.replaceVal && props.replaceVal.orgId) {
    orgId = props.replaceVal.orgId;
  } else {
    orgId = userStore.getOrgInfo.orgId || '0';
  }
  let projectId;
  if (props.replaceVal && props.replaceVal.projectId) {
    projectId = props.replaceVal.projectId;
  } else {
    projectId = props.projectId; //sessionStorage.getItem('__projectId') || '';
  }
  return { projectId, orgId };
});

const itemValueChange = (data: any) => {
  emits('itemValueChange', data);
};

defineExpose({
  getData,
  getBusinessData,
});
</script>
<style lang="less"></style>
